import React from "react";

interface IRepo {
  id: number;
  name: string;
  stargazers_count: number;
  forks_count: number;
}

const App = (): JSX.Element => {
  const [repos, setRepos] = React.useState<IRepo[]>([]);
  const [page, setPage] = React.useState(1);

  const pageDecrement = () => {
    if (page > 1) {
      setPage((prev) => prev - 1);
    }
  };
  const pageIncrement = () => {
    if (repos.length > 0) {
      setPage((prev) => prev + 1);
    }
  };

  React.useEffect(() => {
    fetch(`https://api.github.com/users/facebook/repos?per_page=10&page=${page}`)
      .then((data) => data.json())
      .then((json) => {
        if (json.length) {
          setRepos(json);
        }
      });
  }, [page]);

  if (repos.length === 0) {
    return <div>empty</div>;
  }

  return (
    <div className="App">
      <div>
        <button onClick={pageDecrement}>{"<"}</button>
        {page}
        <button onClick={pageIncrement}>{">"}</button>
      </div>
      {repos?.map((repo, index) => (
        <div key={repo.id} className="repo">
          <a href={`https://github.com/facebook/${repo.name}`} className="title">
            <span className="index">{index + 1}. </span>
            <span className="name">{repo.name}</span>
          </a>
          <div className="content">
            <span className="stars">stars: {repo.stargazers_count}</span>
            <span className="forks">forks: {repo.forks_count}</span>
          </div>
        </div>
      ))}
    </div>
  );
};

export default App;